package java_thinking.unit_21.Exercise.atomic;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerArray;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2019/7/25 19:53
 */

public class AtomicIntegerArrayTest {
    public static void main(String[] args) {
        AtomicIntegerArray array = new AtomicIntegerArray(25);
        array.compareAndSet(2, 0, 65536);
        AtomicInteger integer = new AtomicInteger(10);
        System.out.println(integer);
        WcInteger wcInteger = new WcInteger();
        System.out.println(WcInteger.valueOffset);
        System.out.println(WcInteger.valueOffset1);
        wcInteger.inc();
    }
}

class WcInteger {
    private volatile int value;
    private volatile int value1 = 11;
    private static Unsafe unsafe;
    public static long valueOffset;
    public static volatile long valueOffset1;
    public static volatile long valueOffset3;
    static {
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
            valueOffset = unsafe.objectFieldOffset(WcInteger.class.getDeclaredField("value"));
            valueOffset1 = unsafe.objectFieldOffset(WcInteger.class.getDeclaredField("value1"));
            valueOffset3 = unsafe.objectFieldOffset(WcInteger.class.getDeclaredField("valueOffset1"));
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public int inc(){
        return unsafe.getAndAddInt(this, valueOffset,1)+1;

    }


}
